import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const foodsStore = createSlice({
  name: "foods",
  initialState: {
    foodsList: [],
    activeIndex: 0,
    cartList: [],
  },
  reducers: {
    setFoodsList: (state, action) => {
      state.foodsList = action.payload;
    },
    setActiveIndex: (state, action) => {
      state.activeIndex = action.payload;
    },
    setCartList: (state, action) => {
      const cartItem = state.cartList.find(
        (item) => item.id === action.payload.id
      );
      if (cartItem) {
        cartItem.count++;
      } else {
        state.cartList.push(Object.assign(action.payload, { count: 1 }));
      }
    },
    increCount: (state, action) => {
      const cartItem = state.cartList.find(
        (item) => item.id === action.payload.id
      );
      if (cartItem) {
        cartItem.count++;
      }
    },
    decreCount: (state, action) => {
      const cartItem = state.cartList.find(
        (item) => item.id === action.payload.id
      );
      if (cartItem && cartItem.count > 0) {
        cartItem.count--;
        if (cartItem.count === 0) {
          state.cartList.splice(
            state.cartList.findIndex((item) => item.id === cartItem.id),
            1
          );
        }
      }
    },
  },
});

const { setFoodsList, setActiveIndex, setCartList, increCount, decreCount } =
  foodsStore.actions;
const fetchFoodsList = () => {
  return async (dispatch) => {
    const res = await axios.get("http://localhost:3004/takeaway");
    dispatch(setFoodsList(res.data));
  };
};

export { fetchFoodsList, setActiveIndex, setCartList, increCount, decreCount };
export default foodsStore.reducer;
